import { Inject, makeHttpRequest, Provide } from '@midwayjs/core'
import iconv from 'iconv-lite'
import { isEmpty } from 'lodash-unified'

import { IpService } from './ip.service'

@Provide()
export class AddressService {
  @Inject()
  ipService: IpService

  /** 默认地址 */
  DEFAULT_ADDRESS = 'XX XX'
  /**  请求地址 */
  IP_URL = 'http://whois.pconline.com.cn/ipJson.jsp'

  async getByIp(): Promise<string> {
    const ip = this.ipService.getByCtx()

    if (/127.0.0.1/.test(ip)) {
      return '内网IP'
    }

    const { data } = await makeHttpRequest(`${this.IP_URL}?${ip}&json=true`)

    if (isEmpty(data)) {
      return this.DEFAULT_ADDRESS
    }

    const str = iconv.decode(Buffer.from(data as any, 'binary'), 'GBK')
    const { pro, city, addr } = JSON.parse(str)

    if (pro && city) {
      return `${pro} ${city}`
    } else {
      return addr
    }
  }
}
